package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustomizeException;
import com.heima.common.exception.CustomizeExceptionBuilder;
import com.heima.feign.clients.ArticleClient;
import com.heima.feign.clients.WemediaClient;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.IApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class ApUserRealnameService extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements IApUserRealnameService {
    /**
     * 查询列表
     * @param authDTO
     * @return
     */
    @Override
    public ResponseResult loadListByStatus(AuthDTO authDTO) {
        //1.参数检查
        authDTO.checkParam();
        //2.封装查询条件
        LambdaQueryWrapper<ApUserRealname> queryWrapper = Wrappers.lambdaQuery();
        //2.1准备分页条件
        IPage<ApUserRealname> pageQuery = new Page<>(authDTO.getPage(), authDTO.getSize());
            //2.2根据 status 查询  (条件执行封装需要满足 condition)
        queryWrapper.eq(authDTO.getStatus() != null, ApUserRealname::getStatus, authDTO.getStatus());
        //3.执行查询
        IPage<ApUserRealname> pageResult = this.page(pageQuery, queryWrapper);
        //4.封装结果
        return new PageResponseResult(authDTO.getPage(), authDTO.getSize(), pageResult.getTotal(), pageResult.getRecords());
    }

    @Autowired
    private ApUserMapper apUserMapper;
    @Autowired
    private WemediaClient wemediaClient;
    @Autowired
    private ArticleClient articleClient;

    //@Transactional
    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult updateStatusById(AuthDTO authDTO, Short status) {
        //1.校验参数
            //1.1检查 id 是否存在
        if(authDTO.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "实名认证 id 不能为空");
        }
            //1.2根据 id 查询实名认证信息
        ApUserRealname userRealname = this.getById(authDTO.getId());
        //1.3判断实名认证的状态 [1(待审核)、2(审核未通过)、3(审核通过)]
        if (!AdminConstants.WAIT_AUTH.equals(userRealname.getStatus())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_ALLOW, "当前实名认证的状态错误");
        }
            //1.4查询关联的 ApUser 信息
        ApUser apUser = apUserMapper.selectById(authDTO.getId());
        if(apUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "实名认证关联的 APP 用户信息不存在");
        }
        //2.修改实名认证的状态
        userRealname.setStatus(status);
        if(StringUtils.isNotBlank(authDTO.getMsg())){
            userRealname.setReason(authDTO.getMsg());
        }
        this.updateById(userRealname);
        //3.判断实名认证的状态是为通过
        if(AdminConstants.PASS_AUTH.equals(userRealname.getStatus())){
            //3.1开通自媒体账号(自媒体账号大多数信息都来自 APP 用户信息)  
            WmUser wmUser = createWmUser(apUser);
            //3.2创建作者信息(作者信息需要自媒体账户 id 和 APP 用户 id)
            createAuthor(apUser, wmUser);
        }
        return ResponseResult.okResult();
    }

    private void createAuthor(ApUser apUser, WmUser wmUser) {
        //1.根据 APP 用户 id 查询作者信息
        ResponseResult<ApAuthor> queryResult = articleClient.findByUserId(apUser.getId());
        //1.1判断远程调用的状态，是否被熔断降级
        if(queryResult.getCode().intValue() != 0){
            CustomizeExceptionBuilder.builder(AppHttpCodeEnum.REMOTE_SERVER_ERROR, queryResult.getErrorMessage());
        }
            //1.2判断远程调用的结果，是否存在作者脏数据
        if(queryResult.getData() != null){
            CustomizeExceptionBuilder.builder(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "当前 APP 用户对应的作者信息已存在");
        }
        //2.创建作者信息
        ApAuthor apAuthor = new ApAuthor();
        apAuthor.setName(apUser.getName());
        apAuthor.setType(2);    //作者信息【0(爬取的网络数据)、1(签约合作商)、2(自媒体人)】
        apAuthor.setUserId(apUser.getId());
        apAuthor.setCreatedTime(new Date());
        apAuthor.setWmUserId(wmUser.getId());
        ResponseResult saveResult = articleClient.save(apAuthor);
        if(saveResult.getCode().intValue() != 0){
            CustomizeExceptionBuilder.builder(AppHttpCodeEnum.REMOTE_SERVER_ERROR, saveResult.getErrorMessage());
        }
    }

    private WmUser createWmUser(ApUser apUser) {
        //1.根据 APP 用户名查询自媒体账号
        ResponseResult<WmUser> queryResult = wemediaClient.findByName(apUser.getName());
            //1.1判断远程调用是否熔断降级
        if(queryResult.getCode().intValue() != 0){
            CustomizeExceptionBuilder.builder(AppHttpCodeEnum.REMOTE_SERVER_ERROR, queryResult.getErrorMessage());
        }
            //1.2判断是否有自媒体账号的脏数据
        if(queryResult.getData() != null){
            CustomizeExceptionBuilder.builder(AppHttpCodeEnum.DATA_EXIST, "APP 用户对应的自媒体账户已经存在");
        }
        //2.开通自媒体账户
        WmUser wmUser = new WmUser();
        wmUser.setApUserId(apUser.getId());
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword());
        wmUser.setSalt(apUser.getSalt());
        wmUser.setImage(apUser.getImage());
        wmUser.setPhone(apUser.getPhone());
        wmUser.setStatus(9);    //自媒体账号状态 【0(暂时不可用)、1(永久不可用)、9(正常可用)】
        wmUser.setType(0);  //自媒体账号类型 【0(个人)、1(企业)、2(子账号)】
        wmUser.setCreatedTime(new Date());
        ResponseResult<WmUser> saveResult = wemediaClient.save(wmUser);
        if(saveResult.getCode().intValue() != 0){
            CustomizeExceptionBuilder.builder(AppHttpCodeEnum.REMOTE_SERVER_ERROR, saveResult.getErrorMessage());
        }
        //【测试分布式事务】CustomizeExceptionBuilder.builder(AppHttpCodeEnum.SERVER_ERROR, "自定义服务模组变化");
        return saveResult.getData();
    }
}